#coding=utf-8

from core.scanner import FilterManager
from core.meta import MeepoRequest
from core.ViewMaker import ViewMaker
from utils.jwter import JwtGenerator


#@FilterManager.register('jwt',global_=True)
@FilterManager.register('jwt')
def jwt_filter(httpReq):
    if not isinstance(httpReq, MeepoRequest):
        return ViewMaker.httpStatusView(500, "httpReq is not Servlet Request !")
    request_header = httpReq.get_header()
    auth_str = request_header.get('Authorization')
    if auth_str is None:
        return ViewMaker.httpStatusView(403, "Forbidden!")
    auth_code_list = auth_str.split(' ')
    if len(auth_code_list) not in [2,3]:
        return ViewMaker.httpStatusView(403, "Forbidden!")
    auth_code = auth_code_list[-1]
    auth_res = JwtGenerator.vaild(auth_code)
    if auth_res is False:
        return ViewMaker.httpStatusView(403, "Forbidden!")

    httpReq.set_user(auth_res.user_id)
    httpReq.set_session(auth_res.session)
    return ViewMaker.chainView()
